<template>
	<view class="widget-video" :style="{height:videoHeight}">
		<!-- 视频容器 -->
		<view @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd"
			:style="{'marginTop':marginTop+'px','transition':'all .4s'}">
			<view ref="videoItemBox" class="video-item-box" v-for="(item, index) in videoList" :key="index"
				:style="{height:videoHeight}">
				<video :muted="false" @click="$event => {pauseVideo($event, item)}" :id="item.id"
					class="fullscreen-video" :src="item.delayUrl" @error="videoError(item,index)" :controls="false"
					:show-progress="true" :show-fullscreen-btn="false" :show-play-btn="false" :loop="false"
					:poster="item.viedeoCollectionPosterUrl" :show-loading="true" :autoplay="false"
					:show-center-play-btn="false" object-fit="cover" @ended="videoEnd(item,index)"
					@waiting="videoWaiting">
				</video>

				<i :class="['iconfont iconbofang btn-play',currentStatus == 'pause' && currentIndex == index ? 'show' : '']"
					@click="pauseVideo"></i>
					<view class="video-title" @tap.stop="openVideo">
						<view class="user-name">{{item.viedeoCollectionName}}(第{{index+1}}集)</view>
						<view class="video-content">
							<uni-icons style="position: relative;top:8rpx" type="videocam-filled" size="20"
								color="white"></uni-icons>
							<text>《{{item.viedeoCollectionName}}》更新至{{data.length}}集|选集></text>
						</view>
					</view>
			</view>
		</view>

		<!-- 支付弹窗 -->
		<uni-popup ref="buyPopup" background-color="#fff">
			<view>
				<uni-section title="微信支付" type="line" padding>
					<view class="d-flex justify-between">
						<text>感谢您支持作者,购买后可继续观看</text>
					</view>

					<view class="text-red text-bold">注:只能按照顺序依次解锁!</view>
					<uni-grid :column="2" :square="false" :highlight="true" @change="buyProduct"
						style="margin-top: 5rpx;">
						<uni-grid-item v-for="(item, index) in buyProducts" :index="index" :key="index">
							<view class="grid-item-box" style="background-color: #fff;">
								<uni-icons type="weixin" :size="30" color="#777" />
								<text class="text">{{item.text}}</text>
							</view>
						</uni-grid-item>
					</uni-grid>
				</uni-section>
			</view>
		</uni-popup>

		<!-- 看剧弹窗 -->
		<uni-popup ref="viedoPopup" background-color="#fff" @maskClick="$util.wxCanMove(false)">
			<view>
				<uni-section :title="`1-${data.length}集`" type="line" padding>
					<template v-slot:right>
						<view class="d-flex">
							<button class="mr-1" type="warn" size="mini" @tap="openDj">热门短剧</button>
							<button type="primary" class="mr-1" size="mini" @tap="openOrder">订单</button>
							<button type="default" size="mini"
								@tap="$cw.addWx('https://pic.cwyyt.cn/upload/20230813/020814814_2023081313742.png')">客服</button>
						</view>
					</template>

					<view class="content_list">
						<scroll-view scroll-y="true">
							<view class="example-body">
								<view class="tag-view" v-for="(item,index) in data" :key="index"
									@tap="videoPlayChange(item,false,true)">
									<uni-tag v-if="item.videoUrl" :inverted="currentVideo.id!=item.id"
										:text="`第${index+1}集`" type="primary" />
									<uni-tag v-else :text="`第${index+1}集`" />
								</view>
							</view>
						</scroll-view>
					</view>
				</uni-section>
			</view>
		</uni-popup>

		<!-- 订单弹窗 -->
		<uni-popup ref="orderPopup" background-color="#fff" @maskClick="$util.wxCanMove(false)">
			<uni-section title="微信订单" type="line">
				<view class="content_list">
					<scroll-view scroll-y="true">
						<uni-list>
							<order-item v-for="(item,index) in orderDatas" :inputItem="item" :key="index"></order-item>
						</uni-list>
						<view v-if="orderDatas.length==0" class="text-center">暂无数据...</view>
					</scroll-view>
				</view>
			</uni-section>
		</uni-popup>

		<!-- 热门短剧 -->
		<uni-popup ref="djPopup" background-color="#fff" @maskClick="$util.wxCanMove(false)">
			<uni-section title="热门短剧" type="line">
				<view class="content_list" style="background-color: rgb(241, 241, 241);">
					<uni-search-bar v-model="searchText" radius="100" cancelButton="none" placeholder="输入编号或名称搜索"
						 @clear="searchText=''"  />
					<scroll-view scroll-y="true">
						<uni-list>
							<video-item v-for="(item,index) in calDjDatas" :inputItem="item" :key="index"></video-item>
						</uni-list>
					</scroll-view>
				</view>
			</uni-section>
		</uni-popup>

	</view>
</template>

<script>
	import wx from "@/lib/weixin-js-sdk/index.js";
	import WXPayOrder from '@/service/02WX/WXPayOrderAppService.js';
	import DJViedeoCollection from '@/service/70DJ/DJViedeoCollectionAppService.js';
	export default {
		props: {
			// 视频容器高度
			videoHeight: {
				type: String,
				default: '100vh'
			},
			// 列表数据
			data: {
				type: Array,
				default () {
					return []
				}
			}
		},
		data() {
			return {
				buyProducts: [{
						id: '990',
						text: '9.9元解锁全集',
						videos: 1000
					},
					{
						id: '500',
						text: '5元解锁25集',
						videos: 25
					},
					{
						id: '300',
						text: '3元解锁10集',
						videos: 10
					},
					{
						id: '100',
						text: '1元解锁2集',
						videos: 2
					}
				],
				// 视频列表数据
				videoList: this.data, // .slice(0,2)
				// 视频实际高度，用于滚动计算
				videoRealHeight: 0,
				// 触摸开始值
				startY: 0,
				// 触摸移动值
				moveY: 0,
				// 滑动开始时间
				startTime: 0,
				// 滑动方向
				moveDirection: '',
				// 当前页的视频对象
				currentVideo: null,
				// 视频状态：播放/暂停
				currentStatus: 'pause',
				// 订单数据
				orderDatas: [],
				// 短剧数据
				djDatas: [],
				// 查询
				searchText:''
			};
		},
		// 不要set的数据 统一用computed实现(能用computed 实现的 尽量用他实现 不要用data和method处理) 有返回值的不需要传参的method用computed实现
		computed: {
			currentIndex() {
				return this.videoList.findIndex(x => x.id == this.currentVideo?.id);
			},
			marginTop() {
				return -1 * this.currentIndex * this.videoRealHeight;
			},
			calDjDatas(){
				if(this.searchText){
					return this.djDatas.filter(x=>x.viedeoCollectionSort==this.searchText||
					x.viedeoCollectionName.includes(this.searchText)
					);
				}else{
					return this.djDatas;
				}
			}
		},
		watch: {
			data: {
				handler(n) {
					this.videoList = n;
				},
				deep: true
			}
		},
		mounted() {
			// 初始化视频容器计算高度
			this.videoRealHeight = this.$refs['videoItemBox'][0].$el.getBoundingClientRect().height;
			this.videoPlayChange(this.videoList[0], true);
		},
		methods: {
			openVideo() {
				this.$refs.viedoPopup.open('bottom');
				this.$util.wxCanMove(true);
			},
			openDj() {
				this.getViedeCollections();
				this.$refs.viedoPopup.close();
				this.$refs.djPopup.open('bottom');
				this.$util.wxCanMove(true);
			},
			// 
			async getViedeCollections() {
				let res = await DJViedeoCollection.GetViedeCollections({});
				// 判断接口是正常返回 没有报错
				if (res) {
					this.djDatas = res.datas;
				}
			},
			openOrder() {
				this.getMyWxOrders();
				this.$refs.viedoPopup.close();
				this.$refs.orderPopup.open('bottom');
				this.$util.wxCanMove(true);
			},
			async getMyWxOrders() {
				let res = await WXPayOrder.GetMyWxOrders({});
				// 判断接口是正常返回 没有报错
				if (res) {
					this.orderDatas = res.datas;
				}
			},
			videoWaiting() {
				// uni.showLoading({
				// 	title: '视频加载中...',
				// 	mask: false
				// });
			},
			onHide() {
				this.currentVideo.pause();
				this.currentStatus = 'pause';
			},
			async buyProduct(e) {
				this.$refs.buyPopup.close();
				let {
					index
				} = e.detail;
				const productInfo = this.buyProducts[index];
				const indexVideo = this.videoList.findIndex(x => !x.videoUrl);
				if (indexVideo > -1) {
					let jsCountStr = `${indexVideo+1}`;
					if (productInfo.videos > 1) {
						jsCountStr +=
							`~${(indexVideo+productInfo.videos)>this.videoList.length?this.videoList.length:(indexVideo+productInfo.videos)}`;
					}
					let content = `确认解锁${jsCountStr}集？`;
					const conRes = await this.$cw.showConfirm(content);
					if (conRes) {
						let res = await this.$cw.payOrder(10, productInfo.id, `${productInfo.text}[${jsCountStr}]`,
							this.videoList[0].viedeoCollectionGUID);
						if (res) {
							this.$emit('paySuccess');
						}
					}
				}
			},
			// video结束
			videoEnd(item, index) {
				this.moveY = 999999;
				this.moveDirection = 'down';
				this.touchEnd();
			},
			// 视频出错
			videoError(item, index) {
				// uni.showToast({
				// 	title: '加载出错',
				// 	icon: 'none'
				// })
			},
			// 触摸开始
			touchStart(e) {
				this.startY = e.touches[0].pageY;
				this.startTime = new Date().getTime();
			},
			// 触摸滑动
			touchMove(e) {
				this.moveY = e.touches[0].pageY;
				if (this.moveY > this.startY) {
					this.moveDirection = 'up';
				} else {
					this.moveDirection = 'down';
				}
			},
			// 触摸结束
			touchEnd(e) {
				let millisecond = new Date().getTime() - this.startTime;
				let condition1 = this.moveY > 0 && Math.abs(this.moveY - this.startY) > 50 && millisecond < 500;
				let condition2 = this.moveY > 0 && Math.abs(this.moveY - this.startY) > this.videoRealHeight / 3;
				if (condition1 || condition2) {
					if (this.moveDirection == 'up') {
						if (this.currentIndex > 0) {
							const item = this.videoList[this.currentIndex - 1];
							this.videoPlayChange(item, false, this.moveY == 999999);
						} else {
							this.$cw.showError('无最新');
						}
					} else {
						if (this.currentIndex < (this.videoList.length - 1)) {
							const item = this.videoList[this.currentIndex + 1];
							this.videoPlayChange(item, false, this.moveY == 999999);
						} else {
							this.$cw.showError('看完了');
						}
					}
				}
				this.startY = 0;
				this.moveY = 0;
			},
			// 滑动切换
			videoPlayChange(item, isInit, isNext) {
				this.$refs.viedoPopup.close();
				if (item.videoUrl) {
					let index = this.videoList.findIndex(x => x.id == item.id);
					for (let i = index; i < (index + 3); i++) {
						if (i < this.videoList.length) {
							this.videoList[i].delayUrl = this.videoList[i].videoUrl;
						}
					}

					this.stopOtherVideo();
					this.currentVideo = uni.createVideoContext(item.id, this);
					if (isInit && this.$util.isIos()) {
						// this.currentStatus = 'play';
						// this.$cw.autoPlayVideo(this.currentVideo);
					} else if (!isInit && this.$util.isAndriod()&& !isNext) {
						this.currentStatus = 'play';
						this.currentVideo.play();
						// this.$cw.autoPlayVideo(this.currentVideo);
					} else if (!isInit && isNext && this.$util.isAndriod()) {
						// this.currentStatus = 'play';
						// this.currentVideo.play();
					}
				} else {
					this.$refs.buyPopup.open('bottom');
				}
			},
			// 暂停其他视频
			stopOtherVideo() {
				this.videoList.map(v => {
					let video = uni.createVideoContext(v.id, this);
					video.pause();
					this.currentStatus = 'pause';
				})
			},
			// 暂停/播放视频/双击点赞事件
			pauseVideo(e, item) {
				// 视频对象为空,返回
				if (!this.currentVideo) return;
				if (this.commontShow) {
					this.commontShow = false;
					return;
				}
				clearTimeout(this.clickTimer);
				let currentTime = new Date().getTime();
				let timeRange = currentTime - this.clickTime;
				if (timeRange < 300) {
					// 双击事件
					if (!item.isFabulous) {
						this.$emit('fabulous', item, true);
					}
					this.dbClickAnimation(e);
				} else {
					// 单击事件
					this.clickTimer = setTimeout(() => {
						e.preventDefault();
						e.stopPropagation();
						if (this.currentStatus == 'play') {
							this.currentVideo.pause();
							this.currentStatus = 'pause';
						} else {
							this.currentVideo.play();
							this.currentStatus = 'play';
						}
					}, 300);
				}
				this.clickTime = new Date().getTime();
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content_list {
		height: 850rpx;
		overflow-x: hidden;

		.scroll_view_style {
			height: 100%;
		}
	}

	.grid-item-box {
		flex: 1;
		// position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}

	.example-body {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: flex-start;
		align-items: flex-end;
		flex-wrap: wrap;
	}

	.tag-view {
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}

	@keyframes double-fabulous {
		from {
			opacity: 1;
			transform: scale(1);
		}

		to {
			opacity: 0;
			transform: scale(3);
		}
	}


	// 全局容器
	.widget-video {
		width: 100%;
		height: 100%;
		overflow: hidden;
		position: relative;

		.scroll-video-box {
			min-height: 100%;
			position: relative;

			.empty-txt {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
			}
		}

		// 视频容器
		.video-item-box {
			position: relative;

			.btn-play {
				font-size: 80rpx;
				color: white;
				position: absolute;
				top: 50%;
				left: 50%;
				transition: all .3s;
				transform: translateX(-50%) translateY(-50%) scale(1.5);
				z-index: 8;
				opacity: 0;

				&.show {
					opacity: 0.5;
					transform: translateX(-50%) translateY(-50%) scale(1);
				}
			}

			.fullscreen-video {
				width: 100%;
				height: 100%;
				position: relative;
				object-fit: fill;
			}

			.video-title {
				position: absolute;
				left: 20rpx;
				bottom: 35rpx;
				width: calc(100% - 160rpx);
				color: white;
				z-index: 1;
				line-height: initial;

				.user-name {
					font-weight: bold;
				}

				.video-content {
					font-size: 24rpx;
					height: 60rpx;
				}
			}
		}
	}
</style>